package com.fc.test.shiro.service;

import com.fc.test.mapper.custom.TUserDao;
import com.fc.test.model.auto.TsysUser;
import com.fc.test.model.custom.TUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * describe:参与活动的用户身份校验核心类
 *
 * @author xugang
 * @date 2018/9/19 16:06
 */
@Service
public class EventsShiroRealm extends AuthorizingRealm {

    @Autowired
    private TUserDao tUserDao;

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (token.getPrincipal() == null) {
            return null;
        }
        String mobilePhone = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        // 通过mobilePhone从数据库中查找 User对象，如果找到，没找到.
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法


        TUser userInfo = tUserDao.queryByMobilePhone(mobilePhone);

        System.out.println(userInfo);
        System.out.println("----->>userInfo=" + userInfo.getMobilePhone() + "---" + userInfo.getPassword());
        if (userInfo == null)
            return null;
        else {
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    userInfo, // 用户名
                    userInfo.getPassword(), // 密码
                    getName() // realm name
            );
            return authenticationInfo;
        }
    }

    /**
     * 授权
     * (活动用户无需授权操作)
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
